package com.block.datapush.special.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.account.enums.ActionTypeEnum;
import com.block.account.model.dto.EntryAccountDTO;
import com.block.account.service.impl.AccountItemSpecialServiceImpl;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.service.ICountCommonService;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.datapush.model.result.ApiPushResult;
import com.block.datapush.special.enums.OrderStatusEnum;
import com.block.datapush.special.factory.ApiPushFactory;
import com.block.datapush.special.service.ISpecialCostomInfoService;
import com.block.datapush.special.service.ISpecialDataApiInfoService;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.SpecialCostomInfo;
import com.block.db.entity.SpecialCostomItemInfo;
import com.block.db.entity.SpecialDataApiInfo;
import com.block.db.mapper.SpecialDataApiInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2022-12-03
 */
@Service
public class SpecialDataApiInfoServiceImpl extends ServiceImpl<SpecialDataApiInfoMapper, SpecialDataApiInfo> implements ISpecialDataApiInfoService {

    private static Logger log = LogFactory.getPushLog();

    @Autowired
    ISpecialCostomInfoService specialCostomInfoService;
    @Autowired
    AccountItemSpecialServiceImpl accountItemSpecialService;
    @Autowired
    ICountCommonService countCommonService;
    @Autowired
    NotifyExceptionService notifyExceptionService;


    private SpecialDataApiInfo saveRecord(SpecialCostomInfo costomInfo, SpecialCostomItemInfo itemInfo, MemberExtInfo memberExtInfo) {

        SpecialDataApiInfo apiInfo = new SpecialDataApiInfo();
        apiInfo.setInfoId(costomInfo.getId());
        apiInfo.setDateInfo(LocalDate.now().toString());
        apiInfo.setItemId(itemInfo.getId());
        apiInfo.setPriceAmount(itemInfo.getPriceAmount());
        apiInfo.setChannelCode(memberExtInfo.getChannelCode());
        apiInfo.setChannelName(memberExtInfo.getChannelName());
        apiInfo.setUid(memberExtInfo.getUid());
        apiInfo.setUsername(memberExtInfo.getUsername());
        apiInfo.setMobile(memberExtInfo.getMobile());
        apiInfo.setStatus(OrderStatusEnum.INIT.getValue());

        boolean save = this.save(apiInfo);
        return apiInfo;
    }

    /**
     * 查询需要 更新的用户信息
     */
    @Override
    public ResponseVo queryUpdateApiResult() {
        // 查询待查询的状态的
        List<SpecialDataApiInfo> dataApiInfoList = this.baseMapper.getWaitQueryDataList();
        for (SpecialDataApiInfo dataApiInfo : dataApiInfoList) {
            SpecialCostomInfo costomInfo = specialCostomInfoService.getById(dataApiInfo.getInfoId());

            try {


                // 查询结果
                ApiPushResult apiPushResult = ApiPushFactory.getService(costomInfo.getFactoryType())
                        .queryResult(costomInfo, dataApiInfo, null);

                if (ObjectUtil.isNotEmpty(apiPushResult) && apiPushResult.isSuccess()) {
                    // 查询成功，需要更新结果
                    boolean pushSuccess = false;
                    SpecialDataApiInfo updateEntity = new SpecialDataApiInfo();
                    updateEntity.setId(dataApiInfo.getId());
                    updateEntity.setQueryInfo(apiPushResult.getParam());
                    updateEntity.setQueryResult(apiPushResult.getResult());
                    if (StrUtil.equals(OrderStatusEnum.SUCCESS.getValue(), apiPushResult.getStatus())) {
                        updateEntity.setStatus(OrderStatusEnum.SUCCESS.getValue());
                        pushSuccess = true;
                    } else {
                        // 查询成功的情况下，判断是否已经超过了半个小时，如果超过半个小时，则判定为超时
                        LocalDateTime localDateTime = LocalDateTime.now();
                        LocalDateTime createTime = dataApiInfo.getCreateTime();
                        if (createTime.plusMinutes(30).isBefore(localDateTime)) {
                            updateEntity.setStatus(OrderStatusEnum.TIMEOUT.getValue());
                        }
                    }
                    boolean updateResult = this.updateById(updateEntity);

                    if (pushSuccess && updateResult) {
                        /**
                         * 机构收益统计
                         */
                        CountInfoDTO countInfoDTO = new CountInfoDTO(dataApiInfo.getChannelCode());
                        countInfoDTO.setSpePushCount(1);
                        countInfoDTO.setSpePushAmount(dataApiInfo.getPriceAmount());
                        countCommonService.calculateDataInfo2(countInfoDTO);

                        String billDateInfo = LocalDate.now().toString();
                        EntryAccountDTO entryAccountDTO = new EntryAccountDTO();
                        entryAccountDTO.setInfoId(String.valueOf(dataApiInfo.getInfoId()));
                        entryAccountDTO.setBillDateInfo(billDateInfo);
                        entryAccountDTO.setActionType(ActionTypeEnum.XH.getValue());
                        entryAccountDTO.setChangeAmount(BigDecimal.ZERO.subtract(dataApiInfo.getPriceAmount()));
                        entryAccountDTO.setExtData(String.valueOf(dataApiInfo.getId()));
                        entryAccountDTO.setOperatorId("0");
                        entryAccountDTO.setOperatorName("system");

                        accountItemSpecialService.entryAccountInfo(entryAccountDTO);
                    }
                }
            } catch (Exception exception) {
                notifyExceptionService.notifyNoticeInfo("机构授权回调查询", String.valueOf(dataApiInfo.getInfoId()), String.valueOf(dataApiInfo.getId()), exception);
            }
        }
        return new ResponseVo(AppRspCodeConstant.SUCCESS);
    }

}
